<?php


namespace app\home\controller;


use app\admin\model\CheckInModel;
use app\admin\model\QuanGuanMemberModel;
use app\admin\model\StoreModel;
use app\admin\model\TaskModel;
use app\admin\model\TaskScheduleModel;
use app\admin\validate\Member;
use app\home\services\MemberService;
use app\home\services\TaskService;
use app\utils\Response;

class TaskController extends ApiBase
{
    public function studentGetTaskList()
    {
        $memberService = new MemberService();
        $taskService = new TaskService();
        $taskScheduleModel = new TaskScheduleModel();
        $memberInfo = $memberService->getMemberInfoByToken($this->memberInfo['token'], ['id', 'store_id', 'coach_id']);
        // 默认查询系统任务
        $source = 1;
        if ($memberInfo['store_id'] != 0) {
            // 拳馆id不为空
            $source = 2;
        }
        $taskList = $taskService->getListBySource($source, ['id', 'title', 'type', 'source', 'create_id', 'describe', 'begin_time', 'end_time']);
        foreach ($taskList as $key => &$item) {
            // 如果是教练发布的任务，需要检查学员的教练id是否和任务的发布人为同一个人
            if ($item['source'] == 2 && ($item['create_id'] != $memberInfo['coach_id'])) {
                unset($taskList[$key]);
            }
            $item['over'] = false;
            // 检查任务是否完成
            $taskScheduleInfo = $taskScheduleModel->where([
                'member_id' => $memberInfo['id'],
                'task_id' => $item['id'],
                'task_status' => 2,
            ])->count();
            if ($taskScheduleInfo) {
                $item['over'] = true;
            }
            $item['begin_time'] = date("m月d日", $item['begin_time']);
            $item['end_time'] = date("m月d日", $item['end_time']);
        }

        Response::success([
            'task_list' => array_values($taskList)
        ]);
    }

    /**
     * 教练发布任务/修改
     */
    public function save()
    {
        $maxSize = 10;
        [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
        // 本周开始日期和结束日期
        if ($this->requestData['type'] == 2) {
            // 下周开始日期和结束日期
            [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
            $beginDate = addDaysBydate($beginDate, 7);
            $endDate = addDaysBydate($endDate, 7);
        }
        $beginTime = strtotime($beginDate);
        $endTime = strtotime($endDate);
        $taskModel = new TaskModel();
        $taskService = new TaskService();
        $taskId = 0;
        if (isset($this->requestData['id']) || (int)$this->requestData['id'] > 0) {
            $taskId = $this->requestData['id'];
        }
        if ($this->memberInfo['identity'] != 3) {
            Response::fail("您的身份不是教练");
        }
        $taskCount = $taskModel->where([
            'status' => 1,
            'is_delete' => 1,
            'create_id' => $this->memberInfo['id'],
        ])->where('begin_time', '>=', $beginTime)->where('end_time', '<=', $endTime)->count();
        if ($taskCount >= $maxSize) {
            Response::fail("发布任务数量，超过最大限制");
        }
        $this->requestData['source'] = 2;
        [$code, $msg] = $taskService->save($taskId, $this->memberInfo, $this->requestData);
        if ($code != 0) {
            Response::fail($msg);
        }
        Response::success([], $msg);
    }

    /**
     * 教练获取发布任务的列表
     */
    public function coachGetTaskList()
    {
        [$beginDate1, $endDate1] = getBeginDateAndEndDateByTime(time());
        $beginTime1 = strtotime($beginDate1);
        $endTime1 = strtotime($endDate1);
        [$beginDate2, $endDate2] = getBeginDateAndEndDateByTime(time());
        $beginDate2 = addDaysBydate($beginDate2, 7);
        $endDate2 = addDaysBydate($endDate2, 7);
        $beginTime2 = strtotime($beginDate2);
        $endTime2 = strtotime($endDate2);
        $taskModel = new TaskModel();
        if ($this->memberInfo['identity'] != 3) {
            Response::fail("您的身份不是教练");
        }
        $list = $taskModel->where([
            'status' => 1,
            'is_delete' => 1,
            'create_id' => $this->memberInfo['id'],
        ])->where('begin_time', '>=', $beginTime1)->where('end_time', '<=', $endTime2)->order('end_time', 'asc')->select();
        $return = [];
        foreach ($list as $item) {
            $return[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'describe' => $item['describe'],
                'type' => $item['type'],
                'begin_time' => date("m月d日", $item['begin_time']),
                'end_time' => date("m月d日", $item['end_time']),
            ];
        }
        Response::success([
            'task_list' => $return
        ]);
    }

    /**
     * 馆长获取自己拳馆的任务列表
     */
    public function curatorGetTaskList()
    {
        [$beginDate1, $endDate1] = getBeginDateAndEndDateByTime(time());
        $beginTime1 = strtotime($beginDate1);
        $endTime1 = strtotime($beginDate1);
        [$beginDate2, $endDate2] = getBeginDateAndEndDateByTime(time());
        $beginDate2 = addDaysBydate($beginDate2, 7);
        $endDate2 = addDaysBydate($endDate2, 7);
        $beginTime2 = strtotime($beginDate2);
        $endTime2 = strtotime($endDate2);
        $taskModel = new TaskModel();
        $storeModel = new StoreModel();
        if ($this->memberInfo['identity'] != 4) {
            Response::fail("您的身份不是馆长");
        }
        if (!isset($this->requestData['store_id']) || (int)$this->requestData['store_id'] <= 0) {
            Response::fail("道馆id必传");
        }
        $storeInfo = $storeModel->where([
            'id' => $this->requestData['store_id']
        ])->find();
        if ($storeInfo['member_id'] != $this->memberInfo['id']) {
            Response::fail("您无权查看该信息");
        }
        $list = $taskModel->where([
            'status' => 1,
            'is_delete' => 1,
            'store_id' => $this->requestData['store_id'],
            'source' => 2
        ])->where('begin_time', '>=', $beginTime1)->where('end_time', '<=', $endTime2)->order('end_time', 'asc')->select();
        $return = [];
        $memberModel = new QuanGuanMemberModel();
        foreach ($list as &$item) {
            if ($item['source'] == 2) {
                // 教练名字
                $item['coach_name'] = "";
                $coachInfo = $memberModel->where([
                    'id' => $item['create_id']
                ])->find();
                if (isset($coachInfo['name'])) {
                    $item['coach_name'] = $coachInfo['name'];
                }
                $return[] = [
                    'id' => $item['id'],
                    'title' => $item['title'],
                    'describe' => $item['describe'],
                    'type' => $item['type'],
                    'begin_time' => date("m月d日", $item['begin_time']),
                    'end_time' => date("m月d日", $item['end_time']),
                    'coach_name' => $item['coach_name'],
                ];
            }
        }
        Response::success([
            'task_list' => $return
        ]);
    }

    /**
     * 教练查看自己本周发布任务的完成情况
     */
    public function coachGetTaskOverList()
    {
        $taskModel = new TaskModel();
        $taskScheduleModel = new TaskScheduleModel();
        $memberModel = new QuanGuanMemberModel();
        if ($this->memberInfo['identity'] != 3) {
            Response::fail("您的身份不是教练");
        }
        [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
        $beginTime = strtotime($beginDate);
        $endTime = strtotime($endDate);
        $taskList = $taskModel->where([
            'create_id' => $this->memberInfo['id'],
            'status' => 1,
            'is_delete' => 1,
            'type' => 1,
            'begin_time' => $beginTime,
            'end_time' => $endTime,
        ])->select();
        if (empty($taskList)) {
            Response::fail("您本周没有发布任务哦");
        }
        // 完成的学生
        $overStudentData = [];
        $taskIds = implode(",", array_column($taskList->toArray(), 'id'));
        $taskScheduleList = $taskScheduleModel->where([
            'status' => 1,
            'is_delete' => 1,
            'task_status' => 2,
        ])->whereIn('task_id', $taskIds)->field(['id', 'member_id', 'over_time'])->select();
        if (!$taskScheduleList->isEmpty()) {
            $taskScheduleList = $taskScheduleList->toArray();
            $overStudentData = array_column($taskScheduleList, null, 'member_id');
        }
        $studentField = ['id', 'name', 'image'];
        $studentList = $memberModel->where([
            'status' => 1,
            'is_delete' => 1,
            'coach_id' => $this->memberInfo['id']
        ])->field($studentField)->select();
        foreach ($studentList as &$item) {
            $item['task_over'] = false;
            if (isset($overStudentData[$item['id']])) {
                $item['task_over'] = true;
            }
            $item['image'] = env('DOMAIN_PATH') . $item['image'];
        }
        Response::success([
            'task_list' => $studentList
        ]);
    }

    /**
     * 馆长查看自己道馆学员本周发布任务的完成情况
     */
    public function curatorGetTaskOverList()
    {
        $taskModel = new TaskModel();
        $taskScheduleModel = new TaskScheduleModel();
        $memberModel = new QuanGuanMemberModel();
        if ($this->memberInfo['identity'] != 4) {
            Response::fail("您的身份不是馆长");
        }
        if (!isset($this->requestData['store_id']) || (int)$this->requestData['store_id'] <= 0) {
            Response::fail("道馆id必传");
        }
        $storeId = (int)$this->requestData['store_id'];
        [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
        $beginTime = strtotime($beginDate);
        $endTime = strtotime($endDate);
        $taskIds = $taskModel->where([
            'store_id' => $storeId,
            'status' => 1,
            'is_delete' => 1,
            'type' => 1,
            'begin_time' => $beginTime,
            'end_time' => $endTime,
        ])->field(['id'])->select();
        if ($taskIds->isEmpty()) {
            Response::fail("您本周没有可查看任务哦");
        }
        $taskIdsStr = implode(",", array_column($taskIds->toArray(), 'id'));
        // 完成的学生
        $overStudentData = [];
        $taskScheduleList = $taskScheduleModel->where([
            'status' => 1,
            'is_delete' => 1,
            'task_status' => 2,
        ])->whereIn('task_id', $taskIdsStr)->field(['id', 'member_id', 'over_time'])->select();
        if (!$taskScheduleList->isEmpty()) {
            $taskScheduleList = $taskScheduleList->toArray();
            $overStudentData = array_column($taskScheduleList, null, 'member_id');
        }
        $studentField = ['id', 'name', 'image'];
        $studentList = $memberModel->where([
            'status' => 1,
            'is_delete' => 1,
            'store_id' => $storeId,
            'identity' => 2
        ])->field($studentField)->select();
        foreach ($studentList as &$item) {
            $item['task_over'] = false;
            if (isset($overStudentData[$item['id']])) {
                $item['task_over'] = true;
            }
            $item['image'] = env('DOMAIN_PATH') . $item['image'];
        }
        Response::success([
            'task_list' => $studentList
        ]);
    }

    /**
     * 学生获取排行榜
     */
    public function getRankingList()
    {
        if ($this->memberInfo['identity'] != 2) {
            Response::fail("您的身份不是拳馆学员");
        }
        [$beginDate, $endDate] = getBeginDateAndEndDateByTime(time());
        $beginTime = strtotime($beginDate);
        $endTime = strtotime($endDate);
        $memberModel = new QuanGuanMemberModel();
        $taskScheduleModel = new TaskScheduleModel();
        $taskModel = new TaskModel();
        $storeStudent = $memberModel->where([
            'status' => 1,
            'is_delete' => 1,
            'store_id' => $this->memberInfo['store_id'],
        ])->where('identity', '<', 3)->field(['id', 'name', 'image'])->select();
        if ($storeStudent->isEmpty()) {
            Response::fail("数据异常，请稍后重试");
        }
        // 查询教练本周发布的任务
        $taskInfo = $taskModel->where([
            'create_id' => $this->memberInfo['coach_id'],
            'begin_time' => $beginTime,
            'end_time' => $endTime,
            'status' => 1,
            'is_delete' => 1
        ])->field(['id'])->find();
        $storeStudent = $storeStudent->toArray();
        $storeStudent = array_column($storeStudent, null, 'id');
        $field = ['member_id', 'complete_num'];
        $taskScheduleList = $taskScheduleModel->where([
            'status' => 1,
            'is_delete' => 1,
//            'task_status' => 2,
            'task_id' => $taskInfo['id']
        ])->whereIn('member_id', implode(',', array_keys($storeStudent)))->field($field)->select();
        if (!$taskScheduleList->isEmpty()) {
            $taskScheduleList = $taskScheduleList->toArray();
            $taskScheduleList = array_column($taskScheduleList, null, 'member_id');
        }
        foreach ($storeStudent as &$student) {
            $student['image'] = env('DOMAIN_PATH') . $student['image'];
            $student['complete_num'] = 0;
            if (isset($taskScheduleList[$student['id']]) && $taskScheduleList[$student['id']]['complete_num'] != 0) {
                $student['complete_num'] = $taskScheduleList[$student['id']]['complete_num'];
            }
        }
        $storeStudentList = array_values($storeStudent);
        $completeNumList = array_column($storeStudentList, 'complete_num');
        array_multisort($completeNumList, SORT_DESC, $storeStudentList);
        $studentCurrentData = [];
        foreach ($storeStudentList as $key => &$item) {
            $item['index'] = $key + 1;
            if ($item['id'] == $this->memberInfo['id']) {
                $studentCurrentData = [
                    'image' => env('DOMAIN_PATH') . $item['image'],
                    'index' => $key + 1,
                    'name' => $item['name'],
                    'complete_num' => $item['complete_num']
                ];
            }
        }
        Response::success([
            'student_list' => array_values($storeStudentList),
            'student_current_data' => $studentCurrentData
        ]);
    }

    /**
     * 学员完成项目
     */
    public function studentOverTask()
    {
        if (!isset($this->requestData['id']) || (int)$this->requestData['id'] <= 0) {
            Response::fail("任务id异常");
        }
        if (!isset($this->requestData['num']) || (int)$this->requestData['num'] <= 0) {
            Response::fail("完成次数异常");
        }
        // 查询任务目标
        $taskModel = new TaskModel();
        $taskInfo = $taskModel->where([
            'id' => $this->requestData['id']
        ])->find();
        // 任务目标
        $taskTarget = (int)$taskInfo['task_target'];
        $taskId = (int)$this->requestData['id'];
        $completeNum = (int)$this->requestData['num'];
        $taskScheduleModel = new TaskScheduleModel();
        $taskScheduleInfo = $taskScheduleModel->where([
            'member_id' => $this->memberInfo['id']
        ])->find();
        if (empty($taskScheduleInfo)) {
            $taskScheduleModel->task_id = $taskId;
            $taskScheduleModel->member_id = $this->memberInfo['id'];
            $taskScheduleModel->complete_num = $completeNum;
            $taskScheduleModel->task_status = 1;
            $taskScheduleModel->over_time = 0;
            if ($this->requestData['num'] >= $taskTarget) {
                $taskScheduleModel->task_status = 2;
                $taskScheduleModel->over_time = time();
            }
            $taskScheduleModel->create_time = time();
            $taskScheduleModel->save();
        } else {
            $taskScheduleInfo->complete_num = $completeNum;
            $taskScheduleInfo->task_status = 1;
            $taskScheduleInfo->over_time = 0;
            if ($this->requestData['num'] >= $taskTarget) {
                $taskScheduleInfo->task_status = 2;
                $taskScheduleInfo->over_time = time();
            }
            $taskScheduleInfo->save();
        }
//        $taskScheduleModel->task_id = $taskId;
//        $taskScheduleModel->member_id = $this->memberInfo['id'];
//        $taskScheduleModel->complete_num = $completeNum;
//        $taskScheduleModel->task_status = 1;
//        $taskScheduleModel->over_time = 0;
//        if ($this->requestData['num'] >= $taskTarget) {
//            $taskScheduleModel->task_status = 2;
//            $taskScheduleModel->over_time = time();
//        }
//        $taskScheduleModel->create_time = time();
//        $taskScheduleModel->save();
        Response::success();
    }

    /**
     * 学生获取任务的进度
     */
    public function studentGetTaskCompleteNum()
    {
        if (!isset($this->requestData['task_id']) || (int)$this->requestData['task_id'] <= 0) {
            Response::fail("任务id异常");
        }
        $taskScheduleModel = new TaskScheduleModel();
        $taskScheduleInfo = $taskScheduleModel->where([
            'task_id' => $this->requestData['task_id'],
            'member_id' => $this->memberInfo['id']
        ])->find();
        $completeNum = 0;
        if (!empty($taskScheduleInfo)) {
            $completeNum = $taskScheduleInfo['complete_num'];
        }
        Response::success([
            'complete_num' => $completeNum
        ]);
    }

}